package modellayer;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

/**
 * Write a description of class PersonFileHandler here.
 * 
 * @author (Silas) 
 * @version (12.12.2014)
 */
public class OrdreFileHandler
{
    private String fileName;

    /**
     * Constructor for objects of class PersonFileHandler
     */
    public OrdreFileHandler(String fileName)
    {
        this.fileName = fileName;
    }

    public void saveToFileOrdre(ArrayList<Ordre> ordrer)
    throws IOException
    {
        File destination = makeAbsoluteFilename(fileName);
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(destination));
        os.writeObject(ordrer);
        os.close();
    }

    public ArrayList<Ordre> readFromFileOrdre()
    throws IOException, ClassNotFoundException
    {
        ArrayList<Ordre> returnList = new ArrayList<Ordre>();
        // Make sure the file can be found.
        URL resource = getClass().getResource(fileName);
        if(resource == null) 
        {
            throw new FileNotFoundException(fileName);
        }
        try
        {
            File source = new File(resource.toURI());
            ObjectInputStream is = new ObjectInputStream(
                    new FileInputStream(source));
            returnList = (ArrayList<Ordre>) is.readObject();
            is.close();
        }
        catch(URISyntaxException e)
        {
            throw new IOException("Unable to make a valid filename for " + fileName);
        }
        return returnList;
    }

    private File makeAbsoluteFilename(String filename) throws IOException
    {
        try
        {
            File file = new File(filename);
            if(!file.isAbsolute()) 
            {
                file = new File(getProjectFolder(), filename);
            }
            return file;
        }
        catch(URISyntaxException e)
        {
            throw new IOException("Unable to make a valid filename for " + filename);
        }
    }

    private File getProjectFolder() throws URISyntaxException
    {
        String file = getClass().getName();
        String myClassFile = file.substring(11) + ".class";
        URL url = getClass().getResource(myClassFile);
        return new File(url.toURI()).getParentFile();
    }
}
